package com.progroup.kyrsmoney.service;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

import com.progroup.checks.Checks;
import com.progroup.kyrsmoney.preferences.PreferencesActivity;

	  
public class ServiceExample extends Service {
	public static final int FIRST_RUN = 30000; // 30 seconds
	int REQUEST_CODE = 11223344;
	
	AlarmManager alarmManager;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		startService();
		Log.v(this.getClass().getName(), "onCreate(..)");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.v(this.getClass().getName(), "onBind(..)");
		return null;
	}
	
	@Override
	public void onDestroy() {
		if (alarmManager != null) {
			Intent intent = new Intent(this, AlarmServiceExemple.class);
			alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0));
		}
		
		Log.v(this.getClass().getName(), "Service onDestroy(). Stop AlarmManager at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		startService();
		
	}
	
	
	private void startService() {
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ServiceExample.this);
			Intent intent = new Intent(this, AlarmServiceExemple.class);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
			
			alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
			
			
			int in = Integer.parseInt(pref.getAll().get(PreferencesActivity.INTERVAL_USER_TIME).toString());
			
			long interval = (in+1)*3600000;
			alarmManager.setRepeating(
					AlarmManager.ELAPSED_REALTIME_WAKEUP,
					SystemClock.elapsedRealtime() + FIRST_RUN,
					interval,
					pendingIntent);
			
			
			
			
			/*alarmManager.setRepeating(
				AlarmManager.RTC_WAKEUP,
				Long.parseLong(pref.getAll().get("time_update")+""), 
				AlarmManager.INTERVAL_DAY, 
				pendingIntent);*/
			
			
			Log.v(this.getClass().getName(), "AlarmManger started at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
		
	}
	
	
	
	
	
	
	
	
	
	}